'use strict';

// 甲骨文
const puppeteer = require('puppeteer');

const fs = require('fs');
const https = require('https');
const http = require('http');
const path = require('path');

// 上一级目录的 images 目录路径
const ancientCnTextSaveDir = path.join(__dirname, '..', 'images/ancient_cn_texts');

function downloadImage(url, destPath) {

    if (fs.existsSync(destPath)) {
        console.log('文件存在');
        return;
    }

    const protocol = url.startsWith('https') ? https : http;

    const file = fs.createWriteStream(destPath);
    protocol.get(url, (response) => {
        if (response.statusCode !== 200) {
            console.error('下载失败，状态码:', response.statusCode);
            return;
        }

        response.pipe(file);
        file.on('finish', () => {
            file.close();
            console.log('✅ 下载完成:', destPath);
        });
    }).on('error', (err) => {
        fs.unlink(destPath, () => {
        }); // 删除文件防止残留
        console.error('❌ 下载出错:', err.message);
    });
}

const baseUrl = 'https://www.9610.com/jiagu/bian/';

function craw(htm) {
    const pageUrl = `${baseUrl}${htm}`;
    return new Promise((resolve) => {
        (async () => {
            const browser = await puppeteer.launch();
            const page = await browser.newPage();
            await page.goto(pageUrl);
            await page.setViewport({width: 1080, height: 1024});
            const res = await page.evaluate(async (baseUrl, ancientCnTextSaveDir) => {
                await new Promise((r) => setTimeout(r, 3000));
                let elems = document.querySelectorAll('td');
                const res = [];
                for (let i = 0; i < elems.length; i++) {
                    const elm = elems[i];
                    const imgs = elm.getElementsByTagName('img');
                    if (imgs) {
                        for (let j = 0; j < imgs.length; j++) {
                            const img = imgs[j];
                            const src = img.getAttribute('src');
                            if (elm.innerText.length === 1 && elm.innerText !== "\n") {
                                res.push({
                                    text: elm.innerText,
                                    src,
                                });
                            }
                            // const imgUrl = `${baseUrl}${src}`;
                            // const imgSavePath = ancientCnTextSaveDir + imgName;
                        }
                    }
                }
                return res;
            }, baseUrl, ancientCnTextSaveDir);
            await browser.close();
            resolve(res);
        })();
    });
}

const args = process.argv;
const n = args.length;


if (n >= 2) {
    // const s = 'index.htm,def.htm,gh.htm,jkl.htm,mn.htm,pqr.htm,st.htm,wx.htm,yz.htm';
    // const s = 'index.htm';
    // const s = 'def.htm';
    // const s = 'gh.htm';
    // const s = 'jkl.htm';
    // const s = 'mn.htm';
    // const s = 'pqr.htm';
    // const s = 'st.htm';
    const s = 'wx.htm';
    // const s = 'yz.htm';
    const arr = s.split(',');
    arr.map((s) => {
        craw(s).then((res) => {
            res.map((o) => {
                const {text, src} = o;
                console.log('@@@', text.length)
                const imgName = text + '-' + src;
                const imgUrl = `${baseUrl}${src}`;
                const imgSavePath = ancientCnTextSaveDir + '/' + imgName;
                try {
                    downloadImage(imgUrl, imgSavePath);
                } catch (e) {
                    console.error('err:', imgUrl, imgSavePath, e);
                }
            });
        });
    });
}
